import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button } from 'antd';
import styles from '../Users.css';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import dataImportCreate from '../../addons/DataImport'
const daoName = "CswhED";
const ButtonGroup = Button.Group;
const columns = [
    { title: '考核月份', width: 220, sorter: true, dataIndex: "KHYF", key: 'KHYF', dispaly: false, filter: true, export: true },
    { title: '经营单位', width: 180, sorter: true, dataIndex: 'JYDW', key: 'JYDW', dispaly: true, filter: true, export: true },

    { title: '累计公司额度', width: 120, sorter: true, dataIndex: "LJGSED", key: 'LJGSED', dispaly: true, filter: true, export: true },
    { title: '累计零售额度', width: 120, sorter: true, dataIndex: "LJLSED", key: 'LJLSED', dispaly: true, filter: true, export: true },

    { title: '补发上月额度', width: 120, sorter: true, dataIndex: "BFSYED", key: 'BFSYED', dispaly: true, filter: true, export: true },
    { title: '累计总额度', width: 120, sorter: true, dataIndex: "LJZED", key: 'LJZED', dispaly: true, filter: true, export: true },

    { title: '累计至上月已分配额度', width: 120, sorter: true, dataIndex: "LJZSYFFED", key: 'LJZSYFFED', dispaly: true, filter: true, export: true },
    { title: '本月计算额度', width: 120, sorter: true, dataIndex: "BYJJED", key: 'BYJJED', dispaly: true, filter: true, export: true },

    { title: '本月可分配额度', width: 120, sorter: true, dataIndex: "BYKFPED", key: 'BYKFPED', dispaly: true, filter: true, export: true },
  
   
];
let controls = [
  
   { name: 'KHYF', type: 'month',dataType: "month",required: true, label: '考核月份', grid: 12 / 24 },
   { name: 'JYDW', type: 'text', label: '经营单位',required: true, grid: 12 / 24 },

   { name: 'LJGSED', type: "number", dataType: "number",required: true, label: '累计公司额度', grid: 12 / 24 },
   { name: 'LJLSED', type: "number", dataType: "number",required: true, label: '累计零售额度', grid: 12 / 24 },
   { name: 'BFSYED', type: "number", dataType: "number",required: true, label: '补发上月额度', grid: 12 / 24 },
   { name: 'LJZED', type: "number", dataType: "number",required: true, label: '累计总额度', grid: 12 / 24 },
   { name: 'LJZSYFFED', type: "number", dataType: "number",required: true, label: '累计至上月已分配额度', grid: 12 / 24 },
   { name: 'BYJJED', type: "number", dataType: "number",required: true, label: '本月计算额度', grid: 12 / 24 },
   { name: 'BYKFPED', type: "number", dataType: "number",required: true, label: '本月可分配额度', grid: 12 / 24 },
  
];
let controlsImp = [
 
    { name: 'KHYF', type: 'month',dataType: "month",required: true, label: '考核月份', grid: 12 / 24 },
    { name: 'JYDW', type: 'text', label: '经营单位',required: true, grid: 12 / 24 },
 
    { name: 'LJGSED', type: "number", dataType: "number",required: true, label: '累计公司额度', grid: 12 / 24 },
    { name: 'LJLSED', type: "number", dataType: "number",required: true, label: '累计零售额度', grid: 12 / 24 },
    { name: 'BFSYED', type: "number", dataType: "number",required: true, label: '补发上月额度', grid: 12 / 24 },
    { name: 'LJZED', type: "number", dataType: "number",required: true, label: '累计总额度', grid: 12 / 24 },
    { name: 'LJZSYFFED', type: "number", dataType: "number",required: true, label: '累计至上月已分配额度', grid: 12 / 24 },
    { name: 'BYJJED', type: "number", dataType: "number",required: true, label: '本月计算额度', grid: 12 / 24 },
    { name: 'BYKFPED', type: "number", dataType: "number",required: true, label: '本月可分配额度', grid: 12 / 24 },
   
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
const DataImport = dataImportCreate(daoName);
class EDDRForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "ID", permID: this.props.permID }
        });
        let sort = {
            field: 'ID'
        }
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20, sorter: sort }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    showModelHandler(isAdd) {
        let key = null
        if (!isAdd) {
            const len = this.props.selectedRowKeys.length;
            if (len === 0) {
                message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！',5);
                return;
            }
            key = this.props.selectedRowKeys[len - 1]
        }
        this.props.dispatch({
            type: `${daoName}/openEdit`,
            payload: { key }
        });
    }
    deleteHandler() {
        const keys = this.props.selectedRowKeys;
        const len = keys.length;
        if (len === 0) {
            message.info('请选择要删除的行！',5);
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认要删除选中的${len}行数据吗？`,
            okText: '删除',
            cancelText: '取消',
            onOk: () => {
                this.props.dispatch({
                    type: `${daoName}/remove`,
                    payload: { daoName, keys },
                });
            }
        });
    }
    edidOkHandler() {
        const form = this.refs.OrganForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                let t = `${daoName}/create`
                const { keyName, record } = this.props;
                let msg = "数据添加成功！"
                if (record[keyName]) {
                    values[keyName] = record[keyName];
                    t = `${daoName}/patch`
                    msg = "数据修改成功！"
                }
                controls.map((c, i) => {
                    if (c.type === 'cascader-select') {
                        let vs = values[c.name];
                        if (vs.length > 0) {
                            values[c.name] = vs[vs.length - 1];
                        } else {
                            values[c.name] = null;
                        }
                    }
                    if (c.dataType === "number") {
                        values[c.name] = Number(values[c.name])
                    } else if (c.dataType === "date" || c.dataType === "datetime") {
                        const date = !values[c.name] ? null : new Date(values[c.name])
                        values[c.name] = date ? new Date(date.getFullYear(), date.getMonth(), date.getDate(), 8, 0, 0) : null
                    } else if (c.dataType === "month") {
                        const date = !values[c.name] ? null : new Date(values[c.name])
                        let month = date.getMonth() + 1
                        if (month < 10) {
                            month = "0" + month
                        }
                        values[c.name] = date ? date.getFullYear() + "-" + month : null
                    } else {
                        values[c.name] = values[c.name] === undefined ? null : values[c.name]
                    }
                    if (c.multiple || c.type === 'checkbox-group') {
                        values[c.name] = values[c.name].join(',');
                    }
                })
                this.state.dataChange = true;
                this.props.dispatch({
                    type: t,
                    payload: { daoName, values },
                })
            }
        });
    };
    hideEditHandler() {
        const form = this.refs.OrganForm.getForm();
        form.resetFields();
        if (this.state.dataChange) {
            this.props.dispatch({
                type: `${daoName}/reload`,
                payload: { daoName },
            });
            this.state.dataChange = false;
        }
        this.props.dispatch({
            type: `${daoName}/hideEdit`
        });
    };
    /**
 * 导入
 * 下载导入模板
 */
    //===============================================
    showImportHandler() {
        this.props.dispatch({
            type: `${daoName}_DataImport/setDisplay`,
            payload: { display: true },
        });
    };
    DownTmportHandler() {
        let columnHeaders = []
        columns.map((c) => {
            const name = c.dataIndex ? c.dataIndex : c.key
            // if (!name || name == "bgdt") {
            //     return;
            // }
            if (!name||name=="KHYF") {
                return;
              }
            let header = {
                Name: name,
                Caption: c.title,
                Width: c.width
            }
            columnHeaders.push(header)
        })
        let form = document.createElement('form');//定义一个form表单
        let whereItems = [];
        whereItems.push({
            FieldName: "ID",
            Operator: "=",
            FieldValues: "0"
        })
        const whereCauses = []
        whereCauses.push({
            WhereItems: whereItems,
            RelationSign: "AND"
        })
        const orderItems = []
        form.style = "display:none";
        form.target = "_blank";
        form.method = "post";
        form.action = `/api/ExportXlsx/${daoName}`;
        let input1 = document.createElement("input");
        input1.type = "hidden";
        input1.name = "WhereCauses";
        input1.value = JSON.stringify(whereCauses);
        let input2 = document.createElement("input");
        input2.type = "hidden";
        input2.name = "OrderItems";
        input2.value = JSON.stringify(orderItems)
        let input3 = document.createElement("input");
        input3.type = "hidden";
        input3.name = "ColumnHeaders";
        input3.value = JSON.stringify(columnHeaders);
        let input4 = document.createElement("input");
        input4.type = "hidden";
        input4.name = "PermID";
        input4.value = "" + this.props.permID;
        let input5 = document.createElement("input");
        input5.type = "hidden";
        input5.name = "UserID";
        input5.value = "" + this.props.userID;
        document.body.appendChild(form);//将表单放置在web中
        form.appendChild(input1);
        form.appendChild(input2);
        form.appendChild(input3);
        form.appendChild(input4);
        form.appendChild(input5);
        form.submit();
        document.body.removeChild(form)
    };
    render() {
        let { showEdit, record, permID, popedomTypes, patp } = this.props
        const pTypes = popedomTypes[permID]
        let data = null
        if (pTypes.indexOf("2") !== -1) {
            data = <ButtonGroup style={{ zIndex: 0 }}>
                <Button key="1" onClick={this.showModelHandler.bind(this, true)}>新增</Button>
                <Button key="2" onClick={this.showModelHandler.bind(this, false)}>修改</Button>
                <Button key="3" onClick={this.deleteHandler.bind(this)}>删除</Button>
                <Button key="4" onClick={this.showImportHandler.bind(this)}>导入</Button>
                <Button key="5" onClick={this.DownTmportHandler.bind(this)}>下载导入模板</Button>
            </ButtonGroup>
        }
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div>
                    <div className={styles.create}>
                        {data}
                    </div>
                    <Modal title="额度编辑" width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)} maskClosable={false}
                        footer={[
                            <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
                            <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
                        ]}
                    >
                        <EditFrom ref="OrganForm" daoName={daoName} controls={controls} record={record} />
                    </Modal>
                    <DataTable ref="OrganTable" daoName={daoName} columns={columns} controls={controls} permID={permID} />
                    <DataImport title="额度表" importName="CswhEDImp" daoName={daoName} keys={["ID"]} paramNames={["KHYF"]} importMode="DeleteAfterInsert" controls={controlsImp} forbidConvert={true} saveByDao={true} />
                </div>
            </div>
        )
    }
}
function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
    const { userID, orgID, pOrgID, popedomTypes } = state.menus;
    const { display } = state[`${daoName}_DataImport`];
    return {
        userID,
        orgID,
        pOrgID,
        popedomTypes,
        showEdit,
        selectedRowKeys,
        keyName,
        record,
        showImport: display
    }
}
EDDRForm = connect(mapStateToProps)(EDDRForm)
export default EDDRForm;

let render = (props) => React.createElement(EDDRForm, props);
let f = new Factory()
f.set("EDDRForm", render)